//
//  ProfileViewController.m
//  HelloWorld
//
//  Created by MJiao on 15/6/24.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "ProfileViewController.h"
#include "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "MyAnswerPageModel.h"
#import "MyAnswerTableViewCell.h"
#import "UserManager.h"
#import "CommonUtils.h"
#import "UIImageView+AFNetworking.h"
#import "ImgeUtil.h"
#import "QuestionDetailViewController.h"
#import "Question.h"
#import "DataSourceManager.h"

@interface ProfileViewController ()
/** 用来显示的假数据 */
@property(strong, nonatomic) MyAnswerPageModel *myAnswerPageModel;
@property(nonatomic, assign) BOOL isFristOpen;

@end

@implementation ProfileViewController
- (void)tapDetected {
   
//    NSLog(@"single Tap on imageview");
    [self performSegueWithIdentifier:@"ToEditProfileSegue" sender:self];
}

- (void)reLoin:(NSNotification *)notification {
    NSLog(@"Receve ReLoin notification....");
    [self assembleAvatar];
    self.isLoadedData = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSLog(@"ProfileViewController viewDidLoad");
    //第一次数据加载之前先关闭
    //[self.contentView setHidden:YES];

    self.tableView.estimatedRowHeight = 151.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    [self assembleAvatar];

    //圆角
    self.ivAvatar.layer.masksToBounds = YES;
    self.ivAvatar.layer.cornerRadius = 27.5;


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reLoin:)
                                                 name:@"reLoin"
                                               object:nil];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    singleTap.numberOfTapsRequired = 1;

    [self.ivAvatar setUserInteractionEnabled:YES];
    [self.ivAvatar addGestureRecognizer:singleTap];

    /**
    *  初始化数据集
    */
    if (!self.myAnswerPageModel) {
        self.myAnswerPageModel = [[MyAnswerPageModel alloc] init];
        self.myAnswerPageModel.dataArray = [[NSMutableArray alloc] init];
    }

    self.scrollView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{


        [self.myAnswerPageModel.dataArray removeAllObjects];

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

        NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/help/queryUid?userId=%ld&currentPage=1", [[UserManager shareUserManager] curUser].userId];
        NSLog(@">>urlString:%@", urlString);

        [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

            // 结束刷新
            [self.scrollView.header endRefreshing];

            self.isLoadedData = YES;

            MyAnswerPageModel *tMyAnswerPageModel = [[MyAnswerPageModel alloc] init];

            NSInteger currentPage = [[responseObject objectForKey:@"currentPage"] integerValue];
            NSInteger allPage = [[responseObject objectForKey:@"allPage"] integerValue];

            tMyAnswerPageModel.currentPage = currentPage;
            tMyAnswerPageModel.allPage = allPage;


          NSArray* resultArray = [responseObject objectForKey:@"resultArray"];
          //if (serialization == (id) [NSNull null]
            if (resultArray && resultArray != (id) [NSNull null]  && [resultArray count] !=0) {
                NSArray *resultArray = [[responseObject objectForKey:@"resultArray"] objectAtIndex:0];

                NSString *myPostCount = [NSString stringWithFormat:@"%ld/%ld", [[resultArray objectAtIndex:1] integerValue], [[resultArray objectAtIndex:0] integerValue]];

                // NSString *myPostCount = [NSString stringWithFormat:@"%ld/%ld", [[resultArray objectAtIndex:0] integerValue], [[resultArray objectAtIndex:1] integerValue]];
                
                
                NSString *acceptedCount = [NSString stringWithFormat:@"%ld/%ld", [[resultArray objectAtIndex:3] integerValue], [[resultArray objectAtIndex:2] integerValue]];
                
                [self.lbPostQuestionCount setText:myPostCount];
                [self.lbAcceptionCount setText:acceptedCount];

                //评论数
                [[UserManager shareUserManager] curUser].cnnum = [[resultArray objectAtIndex:2] integerValue];
                [[UserManager shareUserManager] curUser].twnum = [[resultArray objectAtIndex:0] integerValue];


            }else{
                [self.lbPostQuestionCount setText:@"0/0"];
                [self.lbAcceptionCount setText:@"0/0"];
            }
         

            NSArray *result = [responseObject objectForKey:@"result"];

            [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

                NSString *title = [obj objectForKey:@"title"];
                NSInteger userId = [[obj objectForKey:@"userId"] integerValue];
                NSInteger replyCount = [[obj objectForKey:@"plnum"] integerValue];
                NSString *imageUrl = [obj objectForKey:@"imageUrl"];
                NSInteger answerId = [[obj objectForKey:@"id"] integerValue];
                NSString *contents = [obj objectForKey:@"contents"];
                NSString *status = [obj objectForKey:@"status"];
                NSString *createTime = [obj objectForKey:@"createtime"];
                NSString *subjectName = [obj objectForKey:@"subjectName"];
                NSString *gradeName = [obj objectForKey:@"gradeName"];
                NSString *userImage = [obj objectForKey:@"userImage"];
                NSString *sex = [obj objectForKey:@"sex"];
                NSString *userName = [obj objectForKey:@"userName"];
                NSString *slogins = [obj objectForKey:@"slogins"];
                NSInteger questionId = [[obj objectForKey:@"id"] integerValue];
                NSInteger unread = [[obj objectForKey:@"unread"] integerValue];

                NSString *resizedImageUrl = [obj objectForKey:@"resizedImageUrl"];

                NSInteger imageWidth = [[obj objectForKey:@"imageWidth"] integerValue];
                NSInteger imageHeight = [[obj objectForKey:@"imageHeight"] integerValue];

                NSInteger resizedImageWidth = [[obj objectForKey:@"resizedImageWidth"] integerValue];
                NSInteger resizedImageHeight = [[obj objectForKey:@"resizedImageHeight"] integerValue];


                Question *answer = [[Question alloc] init];
                answer.title = title;
                answer.userId = userId;
                answer.imageUrl = imageUrl;
                answer.contents = contents;
                answer.status = status;
                answer.createTime = createTime;
                answer.subjectName = subjectName;
                answer.gradeName = gradeName;
                answer.answerId = answerId;
                answer.replyCount = replyCount;
                answer.userName = userName;
                answer.userImage = userImage;
                answer.slogins = slogins;
                answer.sex = sex;
                answer.imageWidth = imageWidth;
                answer.imageHeight = imageHeight;
                answer.resizedImageWidth = resizedImageWidth;
                answer.resizedImageHeight = resizedImageHeight;
                answer.resizedImageUrl = resizedImageUrl;
                answer.questionId = questionId;
                answer.unread = unread;

                [self.myAnswerPageModel.dataArray addObject:answer];
            }];

            [self refreshBadgeNumber];
            [self.tableView reloadData];
//            [self.tableView setContentSize:CGSizeMake(self.tableView.contentSize.width, self.myAnswerPageModel.dataArray.count*149)];
//            [self.tableView layoutIfNeeded];
//            [self.scrollView layoutIfNeeded];
//            [self.tableView updateConstraintsIfNeeded];
//            [self.scrollView updateConstraintsIfNeeded];

        }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);

            // 结束刷新
            [self.scrollView.header endRefreshing];
        }];


        // 进入刷新状态后会自动调用这个block
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.scrollView.header.autoChangeAlpha = YES;
    //检查当前用户是否已经登录
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }

    //已经与服务器开发人员约定，themeImage的尺寸大小为640x280
    float scaleFactor = 280.0f / 640;
    float constantHeight = scaleFactor * self.ivThemeImage.frame.size.width;
    self.ivThemeImageLayoutConstraint.constant = constantHeight;
    [self.view updateConstraintsIfNeeded];
    [self.view updateConstraintsIfNeeded];


    NSLog(@"constantHeight:%f", constantHeight);
    NSLog(@"self.ivThemeImage.frame.size.width:%f", self.ivThemeImage.frame.size.width);
//
//    // 马上进入刷新状态
//    [self.scrollView.header beginRefreshing];

}

- (void)refreshBadgeNumber {
    long unreadCount = 0;
    for (int idx = 0; idx < [self.myAnswerPageModel.dataArray count]; ++idx) {
        Question *myQuestion = [self.myAnswerPageModel.dataArray objectAtIndex:idx];
        unreadCount += myQuestion.unread;
    }
    NSString *strNotifyNum = nil;
    if (unreadCount != 0) {
        strNotifyNum = [NSString stringWithFormat:@"%ld", unreadCount];
    }
    [[self.tabBarController.tabBar.items objectAtIndex:2] setBadgeValue:strNotifyNum];

    [[DataSourceManager shareDataSourceManager] setNotifyCount:unreadCount];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)assembleAvatar {
    NSString *stringAvatarURL = [CommonUtils serializableIdObject:[[UserManager shareUserManager] curUser].imageUrl defaultValue:@""];

    NSURL *avatarURL = [NSURL URLWithString:stringAvatarURL];
    [self.ivAvatar setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"MyAnswerTableViewCellIdentifier";

    MyAnswerTableViewCell *myAnswerTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (myAnswerTableViewCell == nil) {
        //        answerTableViewCell = [[QuestionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        //将Custom.xib中的所有对象载入
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyAnswerTableViewCell" owner:nil options:nil];
        //第一个对象就是CustomCell了
        myAnswerTableViewCell = [nib objectAtIndex:0];
    }
    // myAnswerTableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
    Question *myQuestion = [self.myAnswerPageModel.dataArray objectAtIndex:[indexPath row]];


    NSString *gradeAndSubject = myQuestion.subjectName;

    NSString *reply = [NSString stringWithFormat:@"%ld回复", (unsigned long) myQuestion.replyCount];

    NSString *status = @"待解决";
    /**
    *  status: 0表示待解决,1表示已解决
    */
    if ([myQuestion.status isEqualToString:@"0"]) {
        status = @"待解决";
        [myAnswerTableViewCell.ivResolveFlag setImage:[UIImage imageNamed:@"usercard_list_ask"]];
    } else if ([myQuestion.status isEqualToString:@"1"]) {
        status = @"已解决";
        [myAnswerTableViewCell.ivResolveFlag setImage:[UIImage imageNamed:@"vote_has_voted"]];
    }

    if (myQuestion.unread == 0) {
        [myAnswerTableViewCell.lbUnread setHidden:YES];
    } else {
        [myAnswerTableViewCell.lbUnread setHidden:NO];
        NSString *strUnread = [NSString stringWithFormat:@"%ld条未读消息", myQuestion.unread];
        [myAnswerTableViewCell.lbUnread setText:strUnread];
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    //"createtime": "2015-07-09 17:32:43",
    [dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:SS"];

    NSString *createTime = myQuestion.createTime;
    @try {
        createTime = [CommonUtils compareCurrentTime:[dateFormat dateFromString:myQuestion.createTime]];
    }
    @catch (NSException *exception1) {
        NSLog(@"Exception occurred: %@, %@", exception1, [exception1 userInfo]);
    }
    NSString *gradeName = [CommonUtils serializableIdObject:myQuestion.gradeName defaultValue:@""];
    [myAnswerTableViewCell.lbGrade setText:gradeName];
    [myAnswerTableViewCell.lbSubject setText:gradeAndSubject];
    [myAnswerTableViewCell.lbCreateTime setText:createTime];
    [myAnswerTableViewCell.lbReplyCount setText:reply];
    [myAnswerTableViewCell.lbStatus setText:status];
    [myAnswerTableViewCell.lbContents setText:myQuestion.contents];


    // NSLog(@"myAnswerTableViewCell.bounds.size.height:%f",myAnswerTableViewCell.bounds.size.height);

    return myAnswerTableViewCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 149;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.myAnswerPageModel.dataArray.count;
//    if(self.myAnswerPageModel.dataArray.count >0){
//        return 1;
//    }
//    return 0;
//    return 1;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    Question *myQuestion = [self.myAnswerPageModel.dataArray objectAtIndex:[indexPath row]];
    self.selectedMyQuestion = myQuestion;
   [self performSegueWithIdentifier:@"ToQuestionDetailSegue" sender:self];
    //查看未读消息后需要刷新
    if (self.selectedMyQuestion.unread != 0) {
        self.isLoadedData = NO;
    }
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

/**
* 传递参数
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"ToQuestionDetailSegue"]) {
        QuestionDetailViewController *destination = segue.destinationViewController;
        [destination setQuestion:self.selectedMyQuestion];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    //检查当前用户是否已经登录
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        if (!self.isFristOpen) {
            [self.noLoginTipView setHidden:NO];
            [self.scrollView setHidden:YES];
        }
        self.isFristOpen = NO;
        return;
    }
    self.lbUserName.text = [[UserManager shareUserManager] curUser].userName;
    [self.noLoginTipView setHidden:YES];
    [self.scrollView setHidden:NO];
    [self assembleAvatar];
    if (self.isLoadedData) {
        [self.tableView reloadData];
        return;
    }
    NSURL *themeImageURL = [NSURL URLWithString:[[UserManager shareUserManager] curUser].themeImage];
    [self.ivThemeImage setImageWithURL:themeImageURL placeholderImage:[UIImage imageNamed:@"myProfile"]];

    //    // 马上进入刷新状态
    [self.scrollView.header beginRefreshing];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnToLoginAction:(id)sender {
    [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
}
@end
